<?php
namespace app\index\controller;
use \think\Controller;
use \think\View;
use \think\Session;
use app\index\model\LoginModel;

class Login extends Controller
{
	public function index()
	{
		return $this->fetch('index');
		// //session_start();
		// if(!session('user_no')){
		// 	return $this->fetch('index');
		// }else{//若已经登录，直接跳转至人脸识别页面
		// 	//return $this->fetch('/face/index');
		// 	return "<script>location.href='".url('index/face/index')."'</script>";
		// }
	}

	public function login_check()
	{
		$user_no = $_REQUEST['user_no'];
		$password = $_REQUEST['password'];
		$login_check = new \app\index\model\LoginModel();
		$user_info = $login_check->login($user_no);
		if($user_info && $user_info['password']==md5($password)){
			// session_start();
			// $_SESSION['user_no'] = $user_info['user_no'];
			// $_SESSION['username'] = $user_info['username'];
			Session::set('user_id',$user_info['id']);
			Session::set('user_no',$user_info['user_no']);
			Session::set('username',$user_info['username']);
			$login_check->update_last_login_time($user_info['user_no']);
			return json(array('code'=>0,'msg'=>url('index/face/index')));
		}else{
			return json(array('code'=>'-30001','msg'=>'账号或密码错误！'));
		}
	}

	public function register()
	{
		return $this->fetch('register');
	}

	public function register_check()
	{
		$data['user_no'] = $_REQUEST['user_no'];
		$data['username'] = $_REQUEST['nickname'];
		$password = $_REQUEST['password'];
		$test = '/^[A-Za-z0-9]{5,15}$/';
		if(!preg_match($test, $data['user_no'])){
			return json(array('code'=>'-30004','msg'=>'账号错误（账号为5-15位且只能为英文和数字）！','data'=>array()));
			exit;
		}
		if(strlen($data['username'])<4 || strlen($data['username'])>15){
			return json(array('code'=>'-30004','msg'=>'昵称长度错误（至少两个汉字或者四个英文或数字）！','data'=>array()));
			exit;
		}
		if(preg_match($test, $password)){
			$register = new \app\index\model\LoginModel();
			if($register->valid_user_no($data['user_no'])){
				return json(array('code'=>'-30001','msg'=>'该账号已存在，请更换一个账号！','data'=>array()));
				exit;
			}
			$data['password'] = md5($password);
			$id = $register->register($data,1);
			if($id){
				return json(array('code'=>'0','msg'=>'注册成功！','data'=>array('url'=>url('index/login/index'))));
			}else{
				return json(array('code'=>'-30002','msg'=>'注册失败，请重试！'.$id,'data'=>array()));
			}
		}else{
			return json(array('code'=>'-30003','msg'=>'密码长度为5-15位且只能为英文和数字！','data'=>array()));
		}
	}

	public function logout()
	{
		Session::set('user_no',"");
		echo "<script>location.href='".url('login/index')."'</script>";
	}

}